package leetCode.sample;

import org.junit.Test;

public class AtoiSolution {

    @Test
    public void test() {
        System.out.println(myAtoi("-   234"));
        System.out.println(myAtoi("-91283472332"));
        System.out.println(myAtoi("-123"));
        System.out.println(myAtoi("4193 with words"));
        System.out.println(myAtoi("42"));
        System.out.println(myAtoi("   -42"));
        System.out.println(myAtoi("-2147483649"));
        System.out.println(myAtoi("-2147483648"));
        System.out.println(myAtoi("2147483648"));
        System.out.println(myAtoi("2147483647"));
        System.out.println(myAtoi("+"));
        System.out.println(myAtoi("words and 987"));
    }

    public int myAtoi(String str) {
        if (str == null || str.isEmpty()) {
            return 0;
        }
        int num = 0;
        Boolean isNegativeNumber = null;
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '-' && isNegativeNumber == null) {
                isNegativeNumber = Boolean.TRUE;
                continue;
            }
            if (chars[i] == '+' && isNegativeNumber == null) {
                isNegativeNumber = Boolean.FALSE;
                continue;
            }
            int temp = (int) chars[i] - (int) ('0');
            if (temp >= 0 && temp < 10) {
                if (isNegativeNumber == null) {
                    isNegativeNumber = Boolean.FALSE;
                }
                if (isNegativeNumber && (Integer.MIN_VALUE / -10 < num || (Integer.MIN_VALUE / -10 == num && temp > 8))) {
                    return Integer.MIN_VALUE;
                } else if (!isNegativeNumber && (Integer.MAX_VALUE / 10 < num || (Integer.MAX_VALUE / 10 == num && temp > 7))) {
                    return Integer.MAX_VALUE;
                }
                num = num * 10 + temp;
                continue;
            }
            if (num == 0 && chars[i] == ' ' && isNegativeNumber == null) {
                continue;
            } else {
                break;
            }
        }
        return num * (isNegativeNumber != null && isNegativeNumber ? -1 : 1);
    }
}
